const Koa = require('koa');
const bodyParser = require('koa-bodyparser')();
const session = require('koa-session-minimal');
const controller = require('./controller')();
const templating = require('./templating');
const rest = require('./rest');
//数据库
global.sequelize = require('./config').connection();
const SessionSetting = require('./session');

const app = new Koa();

app.use(session({
    key: "SESSION_ID",  
    store: SessionSetting.store,
    cookie: SessionSetting.cookie
}));

app.use(async(ctx, next) => {
    if (ctx.path === '/favicon.ico') {
        return;
    }
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    var start = new Date().getTime(),
        execTime;
    await next();
    execTime = new Date().getTime() - start;
    ctx.response.set('X-Response-Time', `${execTime}ms`);
});

const isProduction = process.env.NODE_ENV === 'production';
if (!isProduction) {
    let staticFiles = require('./static-files');
    app.use(staticFiles('/static/', __dirname + '/static'));
}

app.use(bodyParser);

//view
app.use(templating('views', {
    noCache: !isProduction,
    watch: !isProduction
}));

//rest
app.use(rest.restify('/api/'));

//路由控制
app.use(controller);

app.listen(3000);

console.log('app started at port 3000...');